package com.zzstm.oss.controller;

import com.zzstm.commonUtils.R;
import com.zzstm.oss.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/eduoss/fileoss")
@CrossOrigin
public class OssController {

    @Autowired
    private OssService ossService;

    //上传头像
    @PostMapping("/avatar")
    public R uploadOssAvatar(MultipartFile file){
        String oldFileName = file.getOriginalFilename();
        assert oldFileName != null;
        //分隔文件名
        String[] name = oldFileName.split("\\.");
        //拿到后缀
        String suffix = name[1];
        if (!"jpg".equals(suffix) && !"jpeg".equals(suffix) && !"png".equals(suffix) &&
                !"gif".equals(suffix)){
            return R.error().data("msg","上传文件错误");
        }
        //返回头像路径
        String url = ossService.uploadFileAvatar(file);
        return R.ok().data("url",url);
    }

    //上传头像
    @PostMapping("/cover")
    public R uploadOssCover(MultipartFile file){
        String oldFileName = file.getOriginalFilename();
        assert oldFileName != null;
        //分隔文件名
        String[] name = oldFileName.split("\\.");
        //拿到后缀
        String suffix = name[1];
        if (!"jpg".equals(suffix) && !"jpeg".equals(suffix) && !"png".equals(suffix) &&
                !"gif".equals(suffix)){
            return R.error().data("msg","上传文件错误");
        }
        //返回头像路径
        String url = ossService.uploadFileCover(file);
        return R.ok().data("url",url);
    }

}
